var timer;
var seconds = 5;

$(document).ready(function() {
    //Add controls
    $('<div class="controls">' 
        + '<a href="mas-alla-desktop" rel="0"></a>'
        + '<a href="internet-herramienta" rel="1"></a>' 
        + '<a href="mi-idioma" rel="2"></a>'
        + '<a href="vuelta-al-mundo" rel="3"></a>'
        + '<a href="par-tecnologia" rel="4"></a>'
        + '</div>').insertAfter('#carousel .container');
    //Attach functionality to controls
    $('#carousel .controls a').click(function() {
        moveTo($(this).attr('rel'));
        return false;
    });
    $('#carousel').hover(
        function() { //mouseover
            $('#carousel .pause').css('display','block');
            stopTimer();
        }, 
        function() { //mouseout
            $('#carousel .pause').css('display','none');
            startTimer(1); 
        }
    );
    //Set current slide
    setCurrent(0);
    //Start
    startTimer();
});

function setCurrent(slide) {
    $('#carousel .container .slide.current').removeClass('current');
    $('#carousel .controls a.current').removeClass('current');
    $('#carousel .container .slide:nth-child('+(parseInt(slide)+1)+')').addClass('current');
    $('#carousel .controls a:nth-child('+(parseInt(slide)+1)+')').addClass('current');
}

function moveTo(slide) {
    setCurrent(slide);
    $('#carousel .container').animate({left: (-975*slide)+'px'}, 'slow');
}

function startTimer(secs) {
    if(secs)
        timer = setTimeout(timedMove, secs*1000);
    else
        timer = setTimeout(timedMove, seconds*1000);
}

function stopTimer() {
    clearTimeout(timer);
}

function timedMove() {
    var nextSlide = $('#carousel .container .slide').index($('#carousel .slide.current')) + 1;
    if(nextSlide < $('#carousel .container .slide').length)
        moveTo(nextSlide);
    else
        moveTo(0);
    startTimer();
}
